import { init, h } from 'snabbdom'
import className from 'snabbdom/modules/class'
import eventlisteners from 'snabbdom/modules/eventlisteners'
import style from 'snabbdom/modules/style'
import props from 'snabbdom/modules/props'

let patch = init([className, eventlisteners, style, props])

// 页面容器
let wrapper = document.getElementById('wrapper');
const originalData = [
    { rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0 },
    { rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0 },
    { rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0 },
    { rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0 },
    { rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0 },
    { rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0 },
    { rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0 },
    { rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0 },
    { rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0 },
    { rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0 },
]
// 生成原始数据
let data = new Array(10).fill(0).map((_, i) => i).map(index => ({
    index: index + 1,
    content: originalData[index].title,
    time: (new Date()).Format("yyyy-MM-dd hh:mm:ss")
}));

// 将数据转变成js dom树
let vnode = initVnode(data);

// 首次渲染，将虚拟dom结构转变为真实dom结构
patch(wrapper, vnode);

// 得到页面需要渲染的 vnode
function initVnode(data) {
    return h('div.wrap', {
        style: {
            width: '600px',
            margin: '50px auto',
            padding: '20px',
            border: '1px solid #000'
        }
    }, [
        h('header.header-wrap', [
            h('button', { style: { 'margin-right': '10px' }, on: { click: [changeSort, 'order'] } }, 'Ascend'),
            h('button', { style: { 'margin-right': '10px' }, on: { click: [changeSort, 'reorder'] } }, 'Descend'),
            h('button', { style: { 'margin-right': '10px' }, on: { click: [changeSort, 'random'] } }, 'Random'),
            h('button', { on: { click: addItem } }, 'Add Item')
        ]),
        h('table', [
            h('tr', [
                h('th', 'ID'),
                h('th', 'CONTENT'),
                h('th', 'DATE')
            ]),
            h('tbody', data.map(getTrVnode))
        ])
    ]);
}

// 获取表格行的 vnode
function getTrVnode(item) {
    return h('tr', [
        h('td', item.index),
        h('td', item.content),
        h('td', item.time)
    ])
}

// 点击按钮，改变排序
function changeSort(type) {
    if (type === 'order') {
        // 顺序排列
        data.sort((a, b) => a.index - b.index);
    } else if (type === 'reorder') {
        // 倒序排列
        data.sort((a, b) => b.index - a.index);
    } else if (type === 'random') {
        // 随机排列
        data.sort(() => Math.random() > 0.5 ? -1 : 1)
    }
    render(data);
}

// 添加一项
function addItem() {
    const total = data.length;
    const item = {
        index: total,
        content: '-' + total + '--' + randomString(20),
        time: (new Date()).Format("yyyy-MM-dd hh:mm:ss")
    };
    data.unshift(item);
    render(data);
}

// 数据改变，再次渲染
function render(data) {
    vnode = patch(vnode, initVnode(data))
}

// 辅助函数，获取随机字符串
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

